<template>
  <div>
    <a-modal :visible="visible" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" top="10px" width="800px" :mask-closable="false">
      <template #title> 添加渠道 </template>
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <div>
            <div class="title">基础信息</div>
            <a-row>
              <a-col :span="8">
                <a-form-item label="物流商："> {{ info.providerName }} </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="物流名称："> {{ info.expressName }} </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="物流ID："> {{}} </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item field="name" label="渠道名称：" :rules="rules.name">
                  <a-input v-model="form.name" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="code" label="渠道代码：" :rules="rules.code">
                  <a-input v-model="form.code" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="enable" label="状态：" :rules="rules.enable">
                  <a-switch v-model="form.enable">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item label="备注：">
                  <a-input v-model="form.remark" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
          <div>
            <div class="title">绑定仓库</div>
            <div style="margin: 10px 0">
              <a-table size="mini" class="table-singe-line" ref="table" row-key="id" v-model:selected-keys="rowSelectList" :row-selection="rowSelection" :data="houseList" :pagination="false" :scroll="{ x: '100%', y: '280px' }">
                <template #columns>
                  <a-table-column title="仓库ID" #cell="{ record }">
                    {{ record.warehouseCode }}
                  </a-table-column>
                  <a-table-column title="仓库名称" #cell="{ record }">
                    {{ record.warehouseName }}
                  </a-table-column>
                  <a-table-column title="状态" #cell="{ record }">
                    {{ record.status == 1 ? '启用' : '禁用' }}
                  </a-table-column>
                  <a-table-column title="存货类型" #cell="{ record }">
                    {{ record.stockType }}
                  </a-table-column>
                  <a-table-column title="仓库属性" #cell="{ record }">
                    {{ record.warehouseAttribute == 1 ? '国内仓' : '海外仓' }}
                  </a-table-column>
                </template>
              </a-table>
            </div>
          </div>
          <div>
            <div class="title">标发设置</div>
            <div style="margin: 10px 0">
              <a-table size="mini" class="table-singe-line" :data="standardIssueList" :pagination="false" :scroll="{ x: '100%' }">
                <template #columns>
                  <a-table-column title="平台" #cell="{ record }">
                    <a-select placeholder="请选择" v-model="record.shopType">
                      <a-option label="Amazon" value="Amazon"></a-option>
                    </a-select>
                  </a-table-column>
                  <a-table-column title="Carrier" #cell="{ record }">
                    <a-input v-model="record.carrier" />
                  </a-table-column>
                  <a-table-column title="Shipping Service" #cell="{ record }">
                    <a-input v-model="record.shippingMethod" />
                  </a-table-column>
                  <a-table-column title="跟踪号上传方式" #cell="{ record }">
                    <a-select placeholder="请选择" v-model="record.trackNumberType">
                      <a-option label="跟踪号" value="TRACK_NUMBER"></a-option>
                      <a-option label="运单号" value="WAYBILL_NUMBER"></a-option>
                    </a-select>
                  </a-table-column>
                </template>
              </a-table>
            </div>
          </div>
          <div>
            <div class="title">设置地址</div>
            <div>
              <a-row>
                <a-col :span="8">
                  <a-form-item field="name" label="发货地址：">
                    <a-select placeholder="请选择" v-model="form.shipAddressId" @change="changeAddress($event, 'shipAddress')">
                      <a-option v-for="item of shipAddressList" :label="item.name" :value="item.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="code" label="揽收地址：">
                    <a-select placeholder="请选择" v-model="form.collectAddressId" @change="changeAddress($event, 'collectAddress')">
                      <a-option v-for="item of collectAddressList" :label="item.name" :value="item.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="enable" label="退件地址：">
                    <a-select placeholder="请选择" v-model="form.returnAddressId" @change="changeAddress($event, 'returnAddress')">
                      <a-option v-for="item of returnAddressList" :label="item.name" :value="item.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </div>
          <div>
            <div class="title">运费设置</div>
            <div>
              <a-row>
                <a-col>
                  <a-form-item field="enable" label="运费模板：">
                    <a-select @change="changeTem" placeholder="请选择" v-model="form.shipAmountTemplateId">
                      <a-option v-for="item of feeTempalteList" :label="item.name" :value="item.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam, saveOrUpdateExpressChannel, pageExpressAddress, pageExpressFreightTemplate } from '@/api/warehouse'
  import { Message } from '@arco-design/web-vue'
  import { done } from 'nprogress'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['info', 'detailInfo', 'type'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        form: {},
        rules: {
          name: [{ required: true, message: '请输入渠道名称' }],
          code: [{ required: true, message: '请输入渠道代码' }],
        },
        houseList: [],
        rowSelectList: [],
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        standardIssueList: [],
        shipAddressList: [],
        collectAddressList: [],
        returnAddressList: [],
        feeTempalteList: [
          { label: '模板1', id: '模板1' },
          { label: '模板2', id: '模板2' },
          { label: '模板3', id: '模板3' },
        ],
      })

      const open = () => {
        if (props.type == 'add') {
          let obj = {
            carrier: '',
            shippingMethod: '',
            shopType: 'Amazon',
            trackNumberType: '',
          }
          data.standardIssueList = []
          data.standardIssueList.push(obj)
        } else {
          data.form = _.cloneDeep(props.detailInfo)
          data.form.shipAddressId = data.form?.shipAddress?.id || ''
          data.form.collectAddressId = data.form?.collectAddress?.id || ''
          data.form.returnAddressId = data.form?.returnAddress?.id || ''
          data.form.shipAmountTemplateId = data.form?.shipAmountTemplate?.id || ''
          data.rowSelectList = data.form.warehouseList?.map((e: any) => e.id) || []
          data.standardIssueList = data.form.feedConfigList
        }
        getWarehouseList()
        getAddressList()
        getFeeTempalteList()
      }
      const handleOk = (done: any) => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            let provider = {
              expressName: props.info.expressName,
              id: props.info.id,
              providerCode: props.info.providerCode,
              providerName: props.info.providerName,
            }
            data.form.expressProvider = provider
            if (data.enable) data.enable = false
            data.form.warehouseList = []

            data.rowSelectList.forEach((e: any) => {
              let obj: any = {}
              obj.id = e
              data.form.warehouseList.push(obj)
            })

            data.form.feedConfigList = data.standardIssueList

            try {
              const res: any = await saveOrUpdateExpressChannel({ upsertList: [data.form] })
              if (res.code == 'SUCCESS') {
                data.rowSelectList = []
                data.standardIssueList = []
                data.form = {}
                props.type == 'add' ? Message.success('新增成功') : Message.success('设置成功')
                visible.value = false
                emit('save')
              }
              done(true)
            } catch (error) {
              done(true)
            }
          } else {
            done(true)
          }
        })
      }
      const handleCancel = () => {
        data.rowSelectList = []
        data.standardIssueList = []
        data.form = {}
        formRef.value.clearValidate()
        visible.value = false
      }
      // 获取仓库列表
      const getWarehouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res?.data || []
      }

      // 获取地址列表
      const getAddressList = async () => {
        let params = {
          pageNum: 1,
          pageSize: 9999,
        }
        const res = await pageExpressAddress(params)
        data.shipAddressList = []
        data.returnAddressList = []
        data.collectAddressList = []
        res?.data?.records.forEach((e: any) => {
          if (e.type == 'ship') {
            data.shipAddressList.push(e)
          } else if (e.type == 'return') {
            data.returnAddressList.push(e)
          } else if (e.type == 'collect') {
            data.collectAddressList.push(e)
          }
        })
      }

      const changeAddress = (e: any, type: string) => {
        let obj: any = {}
        if (type == 'shipAddress') {
          obj = data.shipAddressList.find((el: any) => el.id == e)
        } else if (type == 'returnAddress') {
          obj = data.returnAddressList.find((el: any) => el.id == e)
        } else {
          obj = data.collectAddressList.find((el: any) => el.id == e)
        }
        let addInfo = {
          id: obj.id,
          name: obj.address,
        }
        data.form[type] = addInfo
      }

      const changeTem = (e: string) => {
        let obj = data.feeTempalteList.find((el: any) => el.id == e)
        let addInfo = {
          id: obj.id,
          name: obj.label,
        }
        data.form['shipAmountTemplate'] = addInfo
      }

      const getFeeTempalteList = async () => {
        let params = {
          pageSize: 99999,
        }
        const res: any = await pageExpressFreightTemplate(params)
        data.feeTempalteList = res?.data?.records
      }

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        changeAddress,
        changeTem,
      }
    },
  })
</script>

<style lang="less" scoped>
  .title {
    position: relative;
    padding-left: 10px;
    height: 30px;
    line-height: 30px;
    font-size: 13px;
    font-weight: 700;
    &::after {
      position: absolute;
      left: 0;
      top: 5px;
      display: inline-block;
      content: '';
      width: 4px;
      height: 20px;
      border-radius: 2px;
      background-color: #165dff;
    }
  }
</style>
